
import com.sun.rowset.JdbcRowSetImpl;
import java.awt.HeadlessException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author TQNINH
 */
public class ContactsFrame extends javax.swing.JFrame {

    private java.sql.Connection cnBook = null;
    private final String url = "jdbc:sqlserver://";
    private final String serverName = "localhost";
    private final String portNumber = "1433";
    private final String instanceName = "SQL11";
    private final String databaseName = "DeveloperApps";
    private final String userName = "sa";
    private final String password = "";
    private Statement stBook = null;
    private long time;
    private boolean editFlag = false;
    private JdbcRowSetImpl jrsBook = null;
    
    /**
     * Creates new form ContactsFrame
     */
    public ContactsFrame() {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            cnBook = java.sql.DriverManager.getConnection(getConnectionUrl(), userName, password);
            if(cnBook != null) {
                JOptionPane.showMessageDialog(null, "Connection successful!");
                stBook = cnBook.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
                ResultSet rsBook = stBook.executeQuery("SELECT * FROM Contacts");
                jrsBook = new JdbcRowSetImpl(rsBook);
            }
        } catch(SQLException e) {
            e.printStackTrace();
        } catch(ClassNotFoundException e) {
            e.printStackTrace();
        }
        initComponents();
        try {
            jrsBook.next();
            fillData(jrsBook);
        } catch(SQLException e) {
            e.printStackTrace();
        }
    }
    
    private String getConnectionUrl() {
        return url + serverName + ":" + portNumber + ";instanceName=" + instanceName + ";databaseName=" + databaseName;
    }
    
    private void fillData(JdbcRowSetImpl j) {
        try {
            txtFirstname.setText(j.getString("FirstName"));
            txtLastname.setText(j.getString("LastName"));
            txaAddress.setText(j.getString("Address"));
            txtPhone.setText(j.getString("Phone"));
            txtBirthdate.setText((j.getDate("Birthdate").toString()));
        } catch(SQLException e) {
            e.printStackTrace();
        }
    }
    
    private void updateData(JdbcRowSetImpl j) {
        try {
            j.updateString("FirstName", txtFirstname.getText());
            j.updateString("LastName", txtLastname.getText());
            j.updateString("Address", txaAddress.getText());
            j.updateLong("Phone", Long.parseLong(txtPhone.getText()));
            if(txtBirthdate.isEditValid()) {
                java.sql.Date d = java.sql.Date.valueOf(txtBirthdate.getText());
                jrsBook.updateDate("Birthdate", d);
            } else {
                String message = "Please enter the date in YYYY-MM-DD format.";
                String title = "Error";
                JOptionPane.showMessageDialog(this, message, title, JOptionPane.ERROR_MESSAGE);
            }
        } catch(SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblMyAddressBook = new javax.swing.JLabel();
        pnlContactDetails = new javax.swing.JPanel();
        lblFirstname = new javax.swing.JLabel();
        lblLastname = new javax.swing.JLabel();
        lblAddress = new javax.swing.JLabel();
        lblPhone = new javax.swing.JLabel();
        lblBirthdate = new javax.swing.JLabel();
        btnPrevious = new javax.swing.JButton();
        btnNext = new javax.swing.JButton();
        txtFirstname = new javax.swing.JTextField();
        txtLastname = new javax.swing.JTextField();
        scpAddress = new javax.swing.JScrollPane();
        txaAddress = new javax.swing.JTextArea();
        txtPhone = new javax.swing.JTextField();
        txtBirthdate = new javax.swing.JFormattedTextField();
        pnlOptions = new javax.swing.JPanel();
        btnNewContact = new javax.swing.JButton();
        btnEditContact = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        btnExit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Address Book");
        setMinimumSize(new java.awt.Dimension(405, 530));
        setResizable(false);
        getContentPane().setLayout(null);

        lblMyAddressBook.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        lblMyAddressBook.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblMyAddressBook.setText("MY ADDRESS BOOK");
        lblMyAddressBook.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        getContentPane().add(lblMyAddressBook);
        lblMyAddressBook.setBounds(10, 4, 380, 40);

        pnlContactDetails.setBorder(javax.swing.BorderFactory.createTitledBorder("Contact Details"));
        pnlContactDetails.setLayout(null);

        lblFirstname.setText("Firstname:");
        pnlContactDetails.add(lblFirstname);
        lblFirstname.setBounds(20, 30, 70, 14);

        lblLastname.setText("Lastname:");
        pnlContactDetails.add(lblLastname);
        lblLastname.setBounds(20, 60, 70, 14);

        lblAddress.setText("Address:");
        pnlContactDetails.add(lblAddress);
        lblAddress.setBounds(20, 90, 70, 14);

        lblPhone.setText("Phone:");
        pnlContactDetails.add(lblPhone);
        lblPhone.setBounds(20, 210, 70, 14);

        lblBirthdate.setText("Birthdate:");
        pnlContactDetails.add(lblBirthdate);
        lblBirthdate.setBounds(20, 240, 70, 14);

        btnPrevious.setText("Previous");
        btnPrevious.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPreviousActionPerformed(evt);
            }
        });
        pnlContactDetails.add(btnPrevious);
        btnPrevious.setBounds(20, 270, 80, 23);

        btnNext.setText("Next");
        btnNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNextActionPerformed(evt);
            }
        });
        pnlContactDetails.add(btnNext);
        btnNext.setBounds(280, 270, 80, 23);

        txtFirstname.setEditable(false);
        pnlContactDetails.add(txtFirstname);
        txtFirstname.setBounds(90, 25, 270, 20);

        txtLastname.setEditable(false);
        pnlContactDetails.add(txtLastname);
        txtLastname.setBounds(90, 55, 270, 20);

        txaAddress.setEditable(false);
        txaAddress.setColumns(20);
        txaAddress.setRows(5);
        scpAddress.setViewportView(txaAddress);

        pnlContactDetails.add(scpAddress);
        scpAddress.setBounds(90, 85, 270, 110);

        txtPhone.setEditable(false);
        pnlContactDetails.add(txtPhone);
        txtPhone.setBounds(90, 205, 270, 20);

        txtBirthdate.setEditable(false);
        pnlContactDetails.add(txtBirthdate);
        txtBirthdate.setBounds(90, 235, 270, 20);

        getContentPane().add(pnlContactDetails);
        pnlContactDetails.setBounds(10, 60, 380, 310);

        pnlOptions.setBorder(javax.swing.BorderFactory.createTitledBorder("Options"));
        pnlOptions.setLayout(null);

        btnNewContact.setText("New Contact");
        btnNewContact.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewContactActionPerformed(evt);
            }
        });
        pnlOptions.add(btnNewContact);
        btnNewContact.setBounds(20, 30, 100, 23);

        btnEditContact.setText("Edit Contact");
        btnEditContact.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditContactActionPerformed(evt);
            }
        });
        pnlOptions.add(btnEditContact);
        btnEditContact.setBounds(130, 30, 100, 23);

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });
        pnlOptions.add(btnSave);
        btnSave.setBounds(280, 30, 80, 23);

        getContentPane().add(pnlOptions);
        pnlOptions.setBounds(10, 380, 380, 70);

        btnExit.setText("Exit");
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });
        getContentPane().add(btnExit);
        btnExit.setBounds(290, 460, 80, 23);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNextActionPerformed
        // TODO add your handling code here:
        try {
            jrsBook.next();
            if(jrsBook.isAfterLast()) {
                btnNext.setEnabled(false);
            } else {
                fillData(jrsBook);
            }
        } catch(SQLException e) {
            e.printStackTrace();
        }
        btnPrevious.setEnabled(true);
    }//GEN-LAST:event_btnNextActionPerformed

    private void btnPreviousActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPreviousActionPerformed
        // TODO add your handling code here:
        try {
            jrsBook.previous();
            if(jrsBook.isBeforeFirst()) {
                btnPrevious.setEnabled(false);
            } else {
                fillData(jrsBook);
            }
        } catch(SQLException e) {
            e.printStackTrace();
        }
        btnNext.setEnabled(true);
    }//GEN-LAST:event_btnPreviousActionPerformed

    private void btnEditContactActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditContactActionPerformed
        // TODO add your handling code here:
        editFlag = true;
        txtFirstname.setEditable(editFlag);
        txtLastname.setEditable(editFlag);
        txaAddress.setEditable(editFlag);
        txtPhone.setEditable(editFlag);
        txtBirthdate.setEditable(editFlag);
        txtFirstname.grabFocus();
    }//GEN-LAST:event_btnEditContactActionPerformed

    private void btnNewContactActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewContactActionPerformed
        // TODO add your handling code here:
        editFlag = false;
        txtFirstname.setEditable(false);
        txtLastname.setEditable(false);
        txaAddress.setEditable(false);
        txtPhone.setEditable(false);
        txtBirthdate.setEditable(false);
        txtFirstname.grabFocus();
        txtFirstname.setText("");
        txtLastname.setText("");
        txaAddress.setText("");
        txtPhone.setText("");
        txtBirthdate.setText("");
    }//GEN-LAST:event_btnNewContactActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        // TODO add your handling code here:
        if((txtFirstname.getText() != null) && (txtLastname.getText() != null)
                && (txaAddress.getText() != null) && (txtBirthdate.getText() != null)
                && (txtPhone.getText() != null)) {
            if(editFlag) {
                try {
                    updateData(jrsBook);
                    jrsBook.updateRow();
                } catch(NumberFormatException e) {
                    e.printStackTrace();
                } catch(HeadlessException e) {
                    e.printStackTrace();
                } catch(SQLException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    jrsBook.moveToInsertRow();
                    updateData(jrsBook);
                    jrsBook.insertRow();
                    jrsBook.moveToCurrentRow();
                    JOptionPane.showMessageDialog(null, "Row inserted!");
                } catch(HeadlessException e) {
                    e.printStackTrace();
                } catch(NumberFormatException e) {
                    e.printStackTrace();
                } catch(SQLException e) {
                    e.printStackTrace();
                }
            }
        } else {
            String message = "Unable to insert blank contact!";
            String title = "Error";
            JOptionPane.showMessageDialog(this, message, title, JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
        // TODO add your handling code here:
        try {
            cnBook.close();
            jrsBook.close();
        } catch(SQLException e) {
            e.printStackTrace();
        }
        System.exit(0);
    }//GEN-LAST:event_btnExitActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ContactsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ContactsFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEditContact;
    private javax.swing.JButton btnExit;
    private javax.swing.JButton btnNewContact;
    private javax.swing.JButton btnNext;
    private javax.swing.JButton btnPrevious;
    private javax.swing.JButton btnSave;
    private javax.swing.JLabel lblAddress;
    private javax.swing.JLabel lblBirthdate;
    private javax.swing.JLabel lblFirstname;
    private javax.swing.JLabel lblLastname;
    private javax.swing.JLabel lblMyAddressBook;
    private javax.swing.JLabel lblPhone;
    private javax.swing.JPanel pnlContactDetails;
    private javax.swing.JPanel pnlOptions;
    private javax.swing.JScrollPane scpAddress;
    private javax.swing.JTextArea txaAddress;
    private javax.swing.JFormattedTextField txtBirthdate;
    private javax.swing.JTextField txtFirstname;
    private javax.swing.JTextField txtLastname;
    private javax.swing.JTextField txtPhone;
    // End of variables declaration//GEN-END:variables
}
